package pl.asoft.nbp.util;

import org.apache.log4j.Logger;
import pl.asoft.nbp.model.ExchangeRate;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by rbiedrawa on 2014-12-01.
 */
public class SiteRunner {

    private static final Logger LOG = Logger.getLogger(SiteRunner.class);
    private static final int THREADS = 30;

    private final List<String> hostList;
    private final DocumentParser documentParser;

    private final String currency;

    public SiteRunner(List<String> hostList, String currency) {
        this.hostList = hostList;
        this.documentParser = new DocumentParser();
        this.currency = currency;
    }

    public void start() {
        if (!hostList.isEmpty()) {
            ExecutorService executor = Executors.newFixedThreadPool(THREADS);

            for (int i = 0; i < hostList.size(); i++) {
                String url = hostList.get(i);
                Runnable worker = new NbpTask(url, currency);
                executor.execute(worker);
            }
            executor.shutdown();
            // we want to wait until all threads are finish, and later we will get
            // the data that we collected
            while (!executor.isTerminated()) {

            }
        }
    }

    public Collection<ExchangeRate> getResults() {
        return documentParser.getExchangeRateTable();
    }

    private class NbpTask implements Runnable {
        private final String url;

        private final String currency;

        public NbpTask(String url, String currency) {
            this.url = url;
            this.currency = currency;
        }

        @Override
        public void run() {
            documentParser.parse(url, currency);
        }
    }
}
